from langchain_core.messages import AIMessage
import uuid


def join_messages(response_content):
    last_index = -1
    empty_count = 0

    for i, content in enumerate(response_content):
        if content == "":
            empty_count += 1
            if empty_count == 5:
                last_index = i  # 连续5个空字符串的最后一个索引
                empty_count = 0  # 重置计数器继续查找
        else:
            empty_count = 0  # 遇到非空字符串重置计数器

    # 重构response_content为连续5个空字符串的最后一个索引到最后一个字符
    if last_index != -1:
        response_content = response_content[last_index + 1:]

    # 如果重构后为空，返回原始内容
    if not response_content:
        response_content = [""]

    # 将response_content拼接为单个字符串
    full_response = "".join(response_content).strip()

    # 返回清理后的响应
    response_content = full_response
    # print("mian end response_content:", response_content)
    return response_content


def join_state(chunk, all_chunks):
    if hasattr(chunk, 'response_metadata') and 'finish_reason' in chunk.response_metadata:
        finish_reason = chunk.response_metadata['finish_reason']
        if finish_reason == 'stop':
            # 如果finish_reason为stop，则结束对话
            res = join_messages(all_chunks)
            # print("join_state res:", res, '/n', all_chunks)
            aim_message = AIMessage(
                content=res,
                additional_kwargs={},
                response_metadata={
                    'finish_reason': 'tool_calls', 'model_name': './qwen3-32b'},
                id=str(uuid.uuid4())  # 生成唯一ID
            )
        else:
            aim_message = ''

    else:
        aim_message = ''
    return aim_message
